package io.renren.common.utils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128; // 可以是128, 192, 或 256

    // 生成AES密钥
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE, new SecureRandom());
        return keyGenerator.generateKey();
    }

    // 加密
    public static String encrypt(String content, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encrypted = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    // 解密
    public static String decrypt(String encryptedContent, SecretKey secretKey) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedContent));
        return new String(original);
    }

    // 辅助方法：从Base64编码的密钥字符串创建SecretKey
    public static SecretKey createSecretKey(String base64Key) throws Exception {
        byte[] decodedKey = Base64.getDecoder().decode(base64Key);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, ALGORITHM);
    }

    /**
     * 将Base64编码的AES密钥字符串转换为SecretKey对象。
     *
     * @param base64EncodedKey Base64编码的AES密钥字符串
     * @return 转换后的SecretKey对象
     * @throws IllegalArgumentException 如果Base64解码失败或密钥长度不正确
     */
    public static SecretKey key2SecretKey(String base64EncodedKey) throws IllegalArgumentException {
        // 解码Base64字符串
        byte[] decodedKey = Base64.getDecoder().decode(base64EncodedKey);

        // 使用解码后的密钥字节和算法名称创建SecretKey对象
        return new SecretKeySpec(decodedKey, "AES");
    }

    public static void main(String[] args) throws Exception {
        SecretKey secretKey = AESUtil.generateKey();
        String key = Base64.getEncoder().encodeToString(secretKey.getEncoded());
        System.out.println("Secret Key: " + key);
        String encrypted = AESUtil.encrypt("123456", secretKey);
        System.out.println("Encrypted: " + encrypted);
        System.out.println("Decrypted: " + AESUtil.decrypt(encrypted, secretKey));

//        byte[] decodedKey = Base64.getDecoder().decode(key);
//        SecretKeySpec aes = new SecretKeySpec(decodedKey, "AES");
//        System.out.println("Secret Key: " + aes);
//        String encrypted1 = AESUtil.encrypt("Hello, World!", aes);
//        System.out.println("Encrypted1: " + encrypted1);
//        System.out.println("Decrypted1: " + AESUtil.decrypt(encrypted1, aes));

    }
}
